using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using PD.ShP.Code;

namespace PD.ShP.Workflows.Features.WorkflowAssociations
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid("cb502731-cc91-4cc9-8b4c-3ecbb19960db")]
    public class WorkflowAssociationsEventReceiver : SPFeatureReceiver
    {
        /// <summary>
        /// Occurs when a Feature is deactivated.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"/> object that represents the properties of the event.</param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            if (web == null)
            {
                return;
            }

            RemoveWorkflowAssotiation(web, PD.ShP.Workflows.WorkflowAssociations.InvoicesAssociation);
        }

        /// <summary>
        /// Removes the workflow assotiation.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="workflowAssociationInformation">The workflow association information.</param>
        private static void RemoveWorkflowAssotiation(SPWeb web, WorkflowAssociationInformation workflowAssociationInformation)
        {
            SPList list = web.GetList(workflowAssociationInformation.ParentListUrl, true);
            IEnumerable<Guid> associationIds = list.WorkflowAssociations
                .OfType<SPWorkflowAssociation>()
                .Where(x => x.BaseTemplate.Id == workflowAssociationInformation.BaseTemplateId)
                .Select(x => x.Id).ToList();
            foreach (Guid associationId in associationIds)
            {
                list.WorkflowAssociations[associationId].Enabled = false;
                list.WorkflowAssociations.Remove(associationId);
            }
        }
    }
}
